// gzip
const { gzip: zopGzip } = require("@gfx/zopfli");
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const productionGzipExtensions = /\.(js|css|svg|woff|ttf|json|html)(\?.*)?$/i; // 需要gzip压缩的文件后缀
const { NODE_ENV } = process.env;

module.exports = (config) => {
  // runtime 代码由于只是驱动不同路由页面的关系,代码量比较少。直接内联到各个js中，减少js数量，少几个请求
  config
    .plugin("ScriptExtHtmlWebpackPlugin")
    .after("html")
    .use("script-ext-html-webpack-plugin", [
      {
        // `runtime` must same as runtimeChunk name. default is `runtime`
        inline: /runtime\..*\.js$/
      }
    ])
    .end();
  config.when(NODE_ENV === "production", (config) => {
    // 代码压缩
    config.optimization.minimize(true);
    // gzip
    config.plugin("compression").use(CompressionWebpackPlugin, [
      {
        cache: true,
        exclude: /.+\.html$/,
        algorithm(input, compressionOptions, callback) {
          return zopGzip(input, compressionOptions, callback);
        },
        compressionOptions: {
          numiterations: 15
        },
        threshold: 5120,
        minRatio: 0.7,
        test: productionGzipExtensions
      }
    ]);
  });
};
